﻿using AutoMapper;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessServices
{
    public class UserServices : IUserServices
    {
        private readonly UnitOfWork _unitOfWork;

        /// <summary>
        /// Public constructor.
        /// </summary>
        public UserServices(UnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// Public method to authenticate user by user name and password.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public int Authenticate(string userName, string password)
        {
            var user = _unitOfWork.UserRepository.Get(u => u.LoginName == userName && u.Password == password);
            if (user != null && user.UserID > 0)
            {
                return user.UserID;
            }
            return 0;
        }
        public BusinessEntities.UserEntity Login(string userName, string password)
        {
            var user = _unitOfWork.UserRepository.Get(u => u.LoginName == userName && u.Password == password && u.IsDelete==false);
            if (user != null && user.UserID > 0)
            {
                //return new BusinessEntities.UserEntityLogin(){
                //    BranchId=user.BranchId,
                //    EmployeeID=user.BranchId,
                //    FullName=user.FullName,
                //    GroupRole=user.GroupRole,
                //    LevelAdmin=user.LevelAdmin,
                //    LoginName=user.LoginName,
                //    State=user.State,
                //  //  Token=user.Tokens.ToList()[0].,
                //    TypeCode=user.TypeCode,
                //    UserID=user.UserID
                //}
                Mapper.CreateMap<User, UserEntity>();
                var userModel = Mapper.Map<User, UserEntity>(user);
                return userModel;
            } 
            return null;
        }
        public bool ValidateToken(string tokenid)
        {
            var token = _unitOfWork.UserRepository.Get(t => t.AuthToken == new System.Guid( tokenid) );
            if (token != null && !token.IsDelete)
            {
                //token.ExpriesOn = token.ExpriesOn.AddSeconds(
                //                              Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
                //_unitOfWork.TokenRepository.Update(token);
                //_unitOfWork.Save();
                return true;
            }
            return false;
        }
    }
}
